<template>
    <div style="display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #4a4652; overflow: hidden">

    </div>
</template>


<script>
import ValidCode from "@/conponents/ValidCode.vue";

export default ({
    name: "FindPassword",
    components: {
        ValidCode
    },
    data() {

        // 自定义校验规则
        const validateCode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入验证码'))
            } else if (this.account.code.toLowerCase() !== this.code) {
                callback(new Error('验证码错误'))
            } else {
                callback()
            }
        };

        // 确认密码校验
        const validatePassword = (rule, confirmPass, callback) => {
            if (confirmPass === '') {
                callback(new Error('请确认密码'))
            } else if (confirmPass !== this.account.password) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        };

        return {
            value: '',      // 用户输入的验证码
            show_num: [],   //
            code: '',       // 验证码值
            account: {
                username: '',
                password: '',
                confirmPass: '',
                email: '',
                role: '用户',
                code: '',     // 用户输入的验证码

            },
            rules: {         // 校验规则
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 4, message: '用户名最少为4个字符', trigger: 'blur'}
                ],
                // password: [
                //     {required: true, message: '请输入密码', trigger: 'blur'},
                //     {min: 6, message: '密码最少为6个字符', trigger: 'blur'}
                // ],
                // confirmPass: [
                //     {validator: validatePassword, trigger: 'blur'}
                // ],
                email: [
                    {required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: 'change'}
                ],
                code: [
                    {validator: validateCode, trigger: 'blur'}
                ]
            }
        }
    },
    mounted() {
        this.show_num = [];
        this.draw();
    },
    methods: {
        // 获取验证码
        getCode(code) {
            this.code = code.toLowerCase();
        },
        findPassword() {
            // 验证码校验
            let [num1 = 0, type, num2 = 0] = this.show_num || [];
            let NUM_MAP = {
                '+': num1 + num2,
                '-': num1 - num2,
                '*': num1 * num2
            }
            if (this.value == null || this.value == '' || this.value.length == 0) {
                this.$message.error('请输入验证码！')
                return;
            }
            if (this.value == NUM_MAP[type]) {

            } else {
                this.$message.error('验证码错误！');
                this.dj()
                return;
            }
            // 校验验证码
            this.$refs['findPasswordRef'].validate((valid) => {
                // 这里需要加入邮箱验证码
                if (valid) {
                    console.log(this.account)
                    // 校验通过

                    // 加密密码处理
                    // let pwd = this.account.password
                    // pwd = this.$md5(pwd)
                    // this.account.password = pwd
                    //  发送  注册  请求
                    this.$request.post('/findPassword', this.account).then(res => {
                        this.account = {}
                        if (res.code === '200') {
                            this.$message.success('密码重置成功！')
                            this.$router.push('/login')
                        } else {
                            this.$message.error(res.msg);
                            // location.reload();
                            this.account.role = '用户'
                        }
                    })
                } else {
                    this.$message.error("输入信息错误!");
                    // location.reload();
                    this.account.role = '用户'
                }
            });
        },
        toLogin() {
            this.$router.push('/login');
        },
        // 随机颜色
        randomColor() {
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);
            return "rgb(" + r + "," + g + "," + b + ")";
        },
        // 绘制干扰（线条，原点）
        drawLine(context, canvas_width, canvas_height) {
            // for (var i = 0; i <= 5; i++) { //验证码上显示线条
            //     context.strokeStyle = this.randomColor();
            //     context.beginPath();
            //     context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
            //     context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
            //     context.stroke();
            // }
            for (var i = 0; i <= 30; i++) { //验证码上显示小点
                context.strokeStyle = this.randomColor();
                context.beginPath();
                var x = Math.random() * canvas_width;
                var y = Math.random() * canvas_height;
                context.moveTo(x, y);
                context.lineTo(x + 1, y + 1);
                context.stroke();
            }
        },
        // 绘制单个字符
        drawStr(context, txt, x) {
            var y = 20 + Math.random() * 8;//文字在canvas上的y坐标（20+0到8的随机数）
            context.font = "bold 23px 微软雅黑";

            context.fillStyle = this.randomColor(); // 随机生成一个颜色
            context.fillText(txt, x, y);
            return x + 10 + context.measureText(txt).width; //宽度
        },
        drawNum(context, randomList, currentWidth) {
            var j = Math.floor(Math.random() * randomList.length);//获取到随机的索引值 Math.floor(Math.random()*(max-min+1)+min);
            var txt = randomList[j];//得到随机的一个内容
            this.show_num.push(txt);
            return this.drawStr(context, txt, currentWidth);
        },
        draw(codeLength = 3) { // codeLength: 设置验证码长度
            let canvas = document.getElementById("canvas");//获取到canvas的对象，演员
            let context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
            let canvas_width = canvas.width;
            let canvas_height = canvas.height;
            context.clearRect(0, 0, canvas_width, canvas_height);

            this.show_num = [];
            let currentWidth = 0;
            // 数字一
            currentWidth = this.drawNum(context, new Array(100).fill(null).map((v, i) => i), currentWidth);
            // 运算类型
            currentWidth = this.drawNum(context, ['+', '-', '*'], currentWidth);
            // 数字二
            currentWidth = this.drawNum(context, new Array(10).fill(null).map((v, i) => i), currentWidth);
            // 绘制= ?
            this.drawStr(context, '= ?', currentWidth)
            // 一些干扰因素（线条，原点）
            this.drawLine(context, canvas_width, canvas_height);
        },

        dj() {
            this.value = ''
            this.draw();
        },
    }
})
</script>

<style>

.input-view {
    height: 43px;
    width: 220px;
    font-size: 20px;
    border: 1px solid #999;
    font-size: 16px;
    padding: 0 10px;
}

.flex-center {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.margin-t20 {
    margin-top: 15px;
}

button {
    background: transparent;
    border: 1px solid #0440b6;
    color: #0440b6;
    margin-right: 10px;
}
</style>